package headfirst.designpatterns.observer.simple;

import java.util.ArrayList;
import java.util.List;

/**
 * 主题
 */
public class SimpleSubject implements Subject {
    private final List<Observer> observers;
    private int value = 0;

    public SimpleSubject() {
        observers = new ArrayList<>();
    }

    @Override
    public void registerObserver(Observer o) {
        observers.add(o);
    }

    @Override
    public void removeObserver(Observer o) {
        observers.remove(o);
    }

    @Override
    public void notifyObservers() {
        for (Observer observer : observers) {
            observer.updateValue(value);
        }
    }

    /**
     * 主题（变量）发生变化
     */
    public void setValue(int value) {
        this.value = value;
        // 通知所有观察者
        this.notifyObservers();
    }

}